package com.xpqh.ksg.modular.auth.service;

import com.xpqh.ksg.common.enums.result.BizExceptionEnum;
import com.xpqh.ksg.common.persistence.dao.KsgUsersMapper;
import com.xpqh.ksg.common.persistence.model.KsgUsers;
import com.xpqh.ksg.common.utils.WechatUtil;
import com.xpqh.ksg.exception.WebApiException;
import common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotBlank;
import java.util.Date;

@Service
@Slf4j
public class AuthService {

    @Autowired
    private WechatUtil wechatUtil;

    @Autowired
    private KsgUsersMapper ksgUsersMapper;

    /**
     * 密码登录
     *
     * @param username
     * @param pwd
     * @return userId
     */
    public String pwdLogin(String username, String pwd) {
        Integer status = ksgUsersMapper.getStatusByPhone(username);
        if (null == status || status == 2) {
            throw new WebApiException(BizExceptionEnum.ACCOUNT_NOT_EXISIT_USE_PHONE_REGISTER);
        } else if (status == 1) {
            throw new WebApiException(BizExceptionEnum.ACCOUNT_LOCKED);
        }
        String userId = ksgUsersMapper.pwdLogin(username, pwd);
        if (!StringUtils.isNotBlank(userId)) {
            throw new WebApiException(BizExceptionEnum.PWD_ERROR);
        }
        return userId;
    }

    // 微信小程序手机号授权注册登录
    @Transactional
    public Integer wechatPhoneLogin(@NotBlank(message = "授权码") String code) throws Exception {
        String phone = wechatUtil.getPhoneNumber(code);
        return phoneLogin(phone);
    }

    // 微信小程序手机号授权注册登录
    @Transactional
    public Integer phoneLogin(@NotBlank(message = "手机号") String phone) {
        Integer status = ksgUsersMapper.getStatusByPhone(phone);
        if (null == status) {
            KsgUsers KsgUsers = new KsgUsers();
            KsgUsers.setCreateDate(new Date());
            KsgUsers.setPoints(0);
            KsgUsers.setUserName("KSG用户");
            KsgUsers.setPhone(phone);
            KsgUsers.setHeadImg("https://oss.h-ksg.com/pc/logo_red_0815.png");
            KsgUsers.setStatus(0);
            KsgUsers.setPassword("123456");
            ksgUsersMapper.insert(KsgUsers);
        } else if (status == 1) {
            throw new WebApiException(BizExceptionEnum.ACCOUNT_LOCKED);
        }

        return ksgUsersMapper.getUserIdByPhone(phone);
    }

    @Transactional
    public void updatePwd(int userId, String pwd, String newPwd) {
        Integer count = ksgUsersMapper.validPwd(userId, pwd);
        if (count == 0) {
            throw new WebApiException(BizExceptionEnum.PWD_ERROR);
        }
        ksgUsersMapper.updatePwd(userId, newPwd);
    }
}

